﻿// ----------------------------------------------------------------------------------
// Microsoft Developer & Platform Evangelism
// 
// Copyright (c) Microsoft Corporation. All rights reserved.
// 
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES 
// OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// ----------------------------------------------------------------------------------
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
// ----------------------------------------------------------------------------------

namespace umbraco.ACSExtensions
{
    using System;
    using System.Globalization;
    using System.Linq;
    using System.Text;
    using System.Web;
    using System.Web.Security;
    using Microsoft.IdentityModel.Claims;
    using Microsoft.IdentityModel.Web;
    using umbraco.cms.businesslogic.member;

    public partial class FederatedLogin : System.Web.UI.UserControl
    {
        public string ReturnUrl
        {
            get
            {
                var returnUrl = this.Request.QueryString["returnUrl"];
                if (string.IsNullOrEmpty(returnUrl))
                {
                    var reqUrl = this.Request.Url;
                    var returnString = new StringBuilder();
                    returnString.Append(reqUrl.Scheme);
                    returnString.Append("://");
                    returnString.Append(this.Request.Headers["Host"] ?? reqUrl.Authority);
                    returnString.Append(this.Request.RawUrl);

                    return returnString.ToString();
                }

                return returnUrl;
            }
        }
        
        public string IdentityProvidersJsonEndpoint
        {
            get { return this.StsIssuerUrl + "/v2/metadata/IdentityProviders.js?protocol=wsfederation&realm=" + HttpUtility.UrlEncode(this.Realm) + "&reply_to=" + HttpUtility.UrlEncode(this.ReturnUrl) + "&context=" + HttpUtility.UrlEncode(this.ReturnUrl) + "&request_id=&version=1.0"; }
        }

        protected string StsIssuerUrl
        {
            get { return FederatedAuthentication.WSFederationAuthenticationModule.Issuer; }
        }

        protected string Realm
        {
            get { return FederatedAuthentication.WSFederationAuthenticationModule.Realm; }
        }

        private bool IsSignInRequest
        {
            get
            {
                if (Request.Form == null || Request.Form["wa"] != "wsignin1.0")
                {
                    return false;
                }

                if (string.IsNullOrEmpty(Request.Form["wresult"]))
                {
                    return !string.IsNullOrEmpty(Request.Form["wresultptr"]);
                }

                return true;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.IsSignInRequest)
            {
                try
                {
                    var claimIdentity = HttpContext.Current.User.Identity as IClaimsIdentity;
                    if (claimIdentity == null)
                    {
                        throw new InvalidOperationException("No Claims Identity found in STS Token.");
                    }

                    var nameIdentifierClaim = claimIdentity.Claims.FirstOrDefault(o => o.ClaimType == ClaimTypes.Name);
                    var emailClaim = claimIdentity.Claims.FirstOrDefault(o => o.ClaimType == ClaimTypes.Email);
                    var identityProviderClaim = claimIdentity.Claims.FirstOrDefault(o => o.ClaimType == ACSExtensionsSettings.IdentityProviderClaimType);

                    if (nameIdentifierClaim == null)
                    {
                        throw new InvalidOperationException("NameIdentifier claim was not found in the provided identity.");
                    }

                    if (identityProviderClaim == null)
                    {
                        throw new InvalidOperationException("The Identity Provider claim was not found in the provided identity.");
                    }

                    if (!ACSExtensionsSettings.IsSignInFromBusinessIdentityProvider(claimIdentity))
                    {
                        // SIGN-IN COMES FROM A "SOCIAL" IP
                        Member member = null;

                        // Check if user is registered using the NameIdentifier
                        var user = Membership.GetUser(nameIdentifierClaim.Value);

                        if (user != null)
                        {
                            member = new Member((int)user.ProviderUserKey);
                            ValidateIdentityProvider(member, identityProviderClaim.Value);
                        }
                        else
                        {
                            // Look for it using EmailAddress
                            if (emailClaim == null)
                            {
                                throw new InvalidOperationException("The Email claim was not found in the provided identity.");
                            }

                            var userName = Membership.GetUserNameByEmail(emailClaim.Value);
                            if (string.IsNullOrEmpty(userName))
                            {
                                throw new InvalidOperationException("The member with specified Email was not found.");
                            }

                            user = Membership.GetUser(userName);
                            member = new Member((int)user.ProviderUserKey);

                            ValidateIdentityProvider(member, identityProviderClaim.Value);

                            // Update LoginName property with NameIdentifier
                            // Set generic properties
                            member.LoginName = nameIdentifierClaim.Value;
                            member.SetGenericProperty(ACSExtensionsSettings.MemberIdentityProviderPropertyAlias, identityProviderClaim.Value);
                            member.SetGenericProperty(ACSExtensionsSettings.MemberIsActivatedPropertyAlias, bool.TrueString);

                            member.Save();
                        }

                        Member.AddMemberToCache(member);
                    }

                    this.Response.Redirect(this.ReturnUrl, true);
                }
                catch (InvalidOperationException ex)
                {
                    // Force the sign out
                    FederatedAuthentication.WSFederationAuthenticationModule.SignOut(false);
                    
                    this.ShowWarning(ex.Message);
                }
            }
        }

        private static void ValidateIdentityProvider(Member member, string identityProvider)
        {
            var storedIdentityProvider = member.GetGenericProperty<string>(ACSExtensionsSettings.MemberIdentityProviderPropertyAlias);
            if (!string.IsNullOrWhiteSpace(storedIdentityProvider) &&
                !identityProvider.Equals(storedIdentityProvider, StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException(
                    string.Format(
                        CultureInfo.InvariantCulture,
                        "The specified member is already registered with another Identity Provider: '{0}'.",
                        storedIdentityProvider));
            }
        }

        private void ShowWarning(string message)
        {
            this.HrdPanel.Visible = false;
            this.ErrorPanel.Visible = true;
            this.ErrorDetails.Text = HttpUtility.HtmlEncode(message);
            this.LoginLink.NavigateUrl = this.ReturnUrl;
        }
    }
}